from odoo import fields, models, api
from odoo.exceptions import UserError
from odoo.addons.rp_customer_management.models.inherit.res_partner_inherit_for_customer import ADDRESS_TYPE


class RPAvailableCustomerAddressTran(models.TransientModel):
    _name = 'rp.available.customer.address.tran'
    _description = "可用客户地址"
    _rec_name = 'rp_acad_code'

    def _default_auto_rp_acad_code(self):
        records = self.env['rp.available.customer.address.tran'].search([])
        return "RP_ACAD" + str(len(records) + 1).zfill(3)

    rp_acad_code = fields.Char(string='索引码', default=_default_auto_rp_acad_code, index=True, copy=False, readonly=True)
    customer_id = fields.Many2one(string='客户', comodel_name='rp.customer', readonly=True)

    first_name = fields.Char(string='名', readonly=True)
    last_name = fields.Char(string='姓', readonly=True)
    phone = fields.Char(string='联系电话', readonly=True)
    street = fields.Char(string='街道', readonly=True)
    email = fields.Char(string='邮箱', readonly=True)
    address_type = fields.Selection(string='地址类型', selection=ADDRESS_TYPE, readonly=True)
    company_name = fields.Char(string='公司名称', readonly=True)

    def action_rewrite_as_sender(self):
        """ 回写发件人 """
        records = self.browse(self.env.context.get('active_ids'))
        if len(records) > 1:
            raise UserError('只能选择一个地址')
        ship_order = self.env['rp.ship.order'].browse(self.env.context.get('ship_order_id'))
        ship_order.write({'send_first_name': records.first_name,
                          'send_last_name': records.last_name,
                          'send_phone': records.phone,
                          'send_street': records.street,
                          'send_address_type': records.address_type,
                          'send_company_name': records.company_name,
                          'send_email': records.email})

    def action_rewrite_as_receiver(self):
        """ 回写收件人 """
        records = self.browse(self.env.context.get('active_ids'))
        if len(records) > 1:
            raise UserError('只能选择一个地址')
        ship_order = self.env['rp.ship.order'].browse(self.env.context.get('ship_order_id'))
        ship_order.write({'receive_first_name': records.first_name,
                          'receive_last_name': records.last_name,
                          'receive_phone': records.phone,
                          'receive_street': records.street,
                          'receive_address_type': records.address_type,
                          'receive_company_name': records.company_name,
                          'receive_email': records.email})
